import axios from "axios";
import router from "@/router/index.js";
import {useTokenStore} from "@/store/user.js";
import {Notification} from '@arco-design/web-vue';

const request = axios.create({
    baseURL: "http://118.24.33.183:8000/api/",
    timeout: 3000,
});

// 请求拦截器
request.interceptors.request.use(config => {
    const tokenStore = useTokenStore();
    if (tokenStore.token) {
        config.headers.set("Authorization", tokenStore.token, false);
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(response => {
    // 判断token是否过期或失效
    if (response.data.code === 401) {
        // 自定义token异常
        Notification.warning(response.data.message);
        router.push("/login");
    }
    return response.data;
}, error => {
    const tokenStore = useTokenStore();
    if (error.message === "Network Error") {
        Notification.warning("服务器请求失败");
        router.push("/login");
    } else if (!tokenStore.token) {
        Notification.warning("token为空，请先登录");
        router.push("/login");
    }
    return Promise.reject(error);
});

export default request;